jQuery(document).ready( function($) {

    function formatNumberWithDynamicDecimals(data,coma=true) {
               // Determine the maximum number of decimal places based on the number's magnitude
               const max_decimals = (Math.abs(data) >= 1) ? 2 : -Math.floor(Math.log10(Math.abs(data)));
               let max_decimals_points=(max_decimals>2)?max_decimals+3:max_decimals;
       
               // Format the number with a maximum of 18 decimal places
               const formattedString = Number(data).toFixed(18);
           
               // Remove trailing zeros and trailing decimal point
               const trimmedString = parseFloat(formattedString).toString().replace(/(\.[0-9]*[1-9])0+$/, '$1').replace(/\.$/, '');
           
               // Check if it's a very small number and format as '0' if needed
               if (trimmedString === '0') {
               return '0.00';
               }
           
               return Number(data).toLocaleString('en-US', {
               minimumFractionDigits:max_decimals_points?Math.max(2, max_decimals_points):2,
               maximumFractionDigits:max_decimals_points?Math.max(2, max_decimals_points):4, // Maximum of 2 decimal places for values greater than one
               useGrouping: coma
               });
    }

    $.fn.glDatatable = function () {
        var $gltbl = $(this);
       var tblId=$gltbl.attr("id");
        var columns = [];
        var fiatcurrency =$gltbl.data('currency');
        var fiatSymbol =$gltbl.data('fiat-currency-symbol');
        var loadCoins =$gltbl.data('load-coins');
        var layout=$gltbl.data("layout");
        var type =$gltbl.data("type");
        var processing_text = $gltbl.data('processing-text');
        var defaultlogo =$gltbl.data("default-logo");
        var classes = $gltbl.data("classes");       
        $gltbl.find('thead th').each(function (index) {
            var index = $(this).data('index');
            var thisTH=$(this);
            //var classes = $(this).data('classes');            
            columns.push({
                data: index,
                name: index,
                render: function (data, type, row, meta) {                    
                    if (meta.settings.json === undefined) { return data; }
                    switch (index) {
                        case 'rank':
                            return  data ;
                            break;
                        case 'name':
                            var singleUrl = thisTH.data('single-url');
                            var url = singleUrl + '/' + row.symbol + '/' + row.coin_id+ '/' + fiatcurrency;
                           
                            var html = `<div class="${classes}">
                            <a  title ="${data}" href = "${url}" style = "position: relative; overflow: hidden;" >
                            <span class="cmc_coin_logo">
                            <img style="width:32px;" id="${data}"  src="${row.logo}"  onerror="this.src ='${defaultlogo}'">
                            </span>
                            <span class="cmc_coin_symbol">(${row.symbol})</span>
                            <br><span class="cmc_coin_name cmc-desktop">${row.name}</span>
                            </a></div>`;

                            return html;

                        case 'price':
                            if (typeof data !== 'undefined' && data !=null){
                                const formatedVal = formatNumberWithDynamicDecimals(data);                                                                                 
                                var custom_price = fiatSymbol+formatedVal;                                
                                return html = '<div data-val="' + row.usd_price + '" class="' + classes + '"><span class="cmc-formatted-price">' + custom_price+'</span></div>';
                         }else{
                                return html = '<div class="'+classes+'>?</div>';
                           }
                            break;
                        case 'percent_change_24h':
                            if (typeof data !== 'undefined' && data != null) {
                            var changesCls = "up";
                                var wrpchangesCls = "cmc-up";
                                if (typeof Math.sign === 'undefined') { Math.sign = function (x) { return x > 0 ? 1 : x < 0 ? -1 : x; } }
                            if (Math.sign(data) == -1) {
                                var changesCls = "down";
                                var wrpchangesCls = "cmc-down";
                            }
                            var html = '<div class="cmc-changes ' + wrpchangesCls+'"><span class="changes '+changesCls+'"><i class="cmc_icon-'+changesCls+'" aria-hidden="true"></i>'+data+'%</span></div>';
                            return html;
                        }else{
                              return html='<div class="cmc-changes">?</span></div>';
                        }
                            break;

                    }
                },
                 "createdCell": function (td, cellData, rowData, row, col) {
                    $(td).attr('data-sort', cellData);
                }  
            });
        });
        $gltbl.DataTable({
            "deferRender": true,
            "language":{
                "processing": processing_text            
                
            },
            "serverSide": true,
            "ajax": {
                "url": gl_data_object.ajax_url,
                "type": "POST",
                "dataType": "JSON",
                "data": function (d) {
                    d.action = "get_top_gl";
                    d.currency = fiatcurrency;
                    d._wpnonce =gl_data_object.nonce;
                    d.loadCoins = loadCoins;
                    d.type = type;
                    // etc
                },
              
                "error": function (xhr, error, thrown) {
                  //  alert('Something wrong with Server');
                }
            },
            "initComplete": function (settings, json) {
            
                if (json?.error == "nonce_failed") {                    
                $(this).find('.dataTables_empty').html("<span style=\"color:red\">Attention: Please exclude this page from your cache plugin, as it is currently causing a nonce failure.<br> For detailed instructions on how to implement the exclusion, kindly follow this link: <a href=\"https://cryptocurrencyplugins.com/docs/coins-marketcap/nonce-validation-failed\" target=\"_balnk\">Exclusion Guide..</a></span>")            

                }
               
                // Hide the custom loader when data is loaded
                $gltbl.removeClass('cmc-table-loader')
                $gltbl.removeClass('cmc-table-loader')
              },
            "ordering":false,
            "paging":   false,
            "info":     false,
            "destroy": true,
            "searching": false,
              "columns": columns,
            "lengthChange": false,
            "dom": '<"top"iflp<"clear">>rt<"bottom"iflp<"clear">>',
             "processing": true,
            "renderer": {
                "header": "bootstrap",
            }
          });
        
}
    $(".cmc-gainer-lossers").each(function(index){
        $(this).glDatatable();
    }); 
  });
